package cn.xej.listener;

import cn.xej.pojo.User;
import com.rabbitmq.client.Channel;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Component;

import java.io.IOException;

/**
 * @Author alicat.xu
 * @Date 2021/10/20 3:50 下午
 */
@Component
public class DirectListener {
    final String queue1 = "queue.direct.test3";
    final String queue2 = "queue.direct.test4";
    final String exchange = "exchange.direct.test2";

    @RabbitListener(bindings = @QueueBinding(
            value = @Queue(queue1),
            exchange = @Exchange(value = exchange),
            key = "routing.A"))
    public void directEvent(User msg, Message message, Channel channel){
        long deliveryTag = message.getMessageProperties().getDeliveryTag();
        try {
            System.out.println(msg+"  "+message);
            String s = new String(message.getBody());
            System.out.println(s);
//            int i = 1/0;
            //消费完成后，手动ack
            channel.basicAck(deliveryTag,false);
        } catch (Exception e) {
            //手动nack
            try {
                channel.basicNack(deliveryTag,false,true);
            } catch (IOException ex) {
                ex.printStackTrace();
            }
        }
    }


    @RabbitListener(bindings = @QueueBinding(
            value = @Queue(queue2),
            exchange = @Exchange(value = exchange),
            key = "routing.B"
    ))
    public void directEvent1(User msg,Message message){
        System.out.println(msg+"  "+message);
    }
}
